﻿using Dataqueay.Commands;
using Dataqueay.Moudels;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Dataqueay.ViewModels
{
    public class PersonListViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public string _serachText;
        public List<Person> _resultList;

        public PersonListViewModel()
        {
            PersonList = Person.GetPeople();
            _resultList = PersonList;

            this.SearchCommand = new QueryCommand();
            this.SearchCommand._execute = new Action<object>(Searching);
        }

        private void OnPropertyChanged(string propName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if(handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propName));
            }
        }

        public List<Person> PersonList { get; set; }

        public string SerachText { 
            get => _serachText;
            set 
            { 
                _serachText = value;
                OnPropertyChanged("SerachText");
            } 
        }
        public List<Person> ResultList
        {
            get => _resultList;
            set 
            {
                _resultList = value;
                OnPropertyChanged("ResultList");
            }
        }

        public QueryCommand SearchCommand { get; set; }

        private void Searching(object obj)
        {
            List<Person> personList = null;
            if(string.IsNullOrEmpty(SerachText))
            {
                ResultList = PersonList;
            }
            else
            {
                personList = new List<Person>();
                foreach(var i in PersonList)
                {
                    if(i.Sex.ToLower().Equals(SerachText) || i.Sex.ToUpper().Equals(SerachText))
                        personList.Add(i);
                    

                    if (personList != null)
                        ResultList = personList;
                }
            }

        }

    }
}
